// page/payOrder/payOrder.js
const {
  $Toast
} = require('../../dist/base/index');
var app = getApp();
const server = require('../../utils/server.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    idArr:[],
    AddrActions:[],
    addrsShowStatus:false,
    walletStatus:false,
    walletList: [{
      "startPeriod": 1538755200000,
      "money": 60,
      "endPeriod": 1540545440000,
      "name": "哈哈",
      "id": 4,
      "meetMoney": 10
    },
      {
        "startPeriod": 1539756636000,
        "money": 2.16,
        "endPeriod": 1540966243000,
        "name": "优惠卷11",
        "id": 5,
        "meetMoney": 5.23
      }],
    total: 0,
    shopId: '',
    addressId: 0,
    curReceivedInfo:{},
    orderInfo: {},
    ids: [],
    remark:'',
    info: {
      username: '李先生',
      phone: '13523450461',
      addr: '河南省洛阳市王城公园',
      shopname: '王牌小龙虾1',
      boxMoney: 2,
      sendMoney: 2,
      said: "少辣 "
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _that = this;
    var imgUrl=wx.getStorageSync('imgUrl');
    _that.getAddrList();
    _that.setData({
      imgUrl:imgUrl,
      addrsShowStatus: false,
    })
    
    // let pages = getCurrentPages();
    // let prevpage = pages[pages.length - 2];
    // if (prevpage.route.indexOf('address') > -1) {
     
    // }
    // var timer1=setInterval(function(){
    //   _that.getAddrList();
    // },500)
    setInterval(function(){
      _that.getAddrList();
    },10000);
    _that.clearCart();
    var shopId = wx.getStorageSync('shopId');
    var data = JSON.parse(options.orderData);
    
    var obj={
      id: data.addressee.id,
      name: data.addressee.name,
      site: data.addressee.site,
      phone: data.addressee.phone,
    }
    _that.setData({
      orderInfo: data,
      total: data.total,
      addressId:data.addressee.id,
      shopId: shopId,
      curReceivedInfo: obj
    });
     
        _that.getOpenId();
      

  },
  clearCart() {
    let uid = wx.getStorageSync('uid');
    let shopId = wx.getStorageSync('shopId');
    let that = this;
    server.postReq('/mobile/shoppingTrolley/deleteShopShoppingTrolley', {
      userId: uid,
      shopId: shopId
    }, function(res) {
      if (res.data.code == 1) {

      }
    })
  },
  onHide() {
    this.clearCart();
  },
  cancelForm(){
    this.setData({
      walletStatus:false,
    })
  },
  minusDis(e){
    let that=this;
    var id=e.currentTarget.dataset.id;
    server.postReq('/mobile/shoppingTrolley/userCoupon',{
      result:that.data.orderInfo.total,
      couponId:id
    },function(res){
      if(res.data.code==1){
        var minus = res.data.data.actualAmount;
        var info=that.data.orderInfo;
        var total = info.total;
        info.total=Number(total)-Number(minus);
        that.setData({
           walletStatus:false,
           orderInfo:info
        })
      }else{
        that.setData({
          walletStatus: false,
          })
      }
    })
  },
  remarkInput: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },
  //优惠
  getMyDis(){
    let that=this;
    server.postReq('/mobile/shoppingTrolley/lookCoupon',{
      userId:wx.getStorageSync('uid'),
      result:that.data.orderInfo.total
    },function(res){
       if(res.data.code==1){
        if(!res.data.data.length){
         
         that.handleText("无可用优惠券");
         return false;
        }else{
          var data = res.data.data;
          for (let i in data) {
           
            data[i].start = server.formatTimeStamp((data[i].startPeriod) / 1000, 'Y/M/D');
            data[i].end = server.formatTimeStamp((data[i].startPeriod) / 1000, 'Y/M/D');
          }
          that.setData({
            walletStatus: true,
            walletList: data
          })
         
        }
       }
    })
  },
  order(options) {

    var that = this;
    if(!that.data.remark){
      that.setData({
        remark:''
      })
    }
    that.clearCart();
    let uid = wx.getStorageSync('uid');
    let shopId = wx.getStorageSync('shopId');
    let ids = wx.getStorageSync('ids');
    server.postReq("/mobile/shoppingTrolley/WaitingForThePayment", {
      userId: uid,
      shopId: shopId, //	string	是	商铺id
      addresseeId: that.data.orderInfo.addressee.id, //string	是	收件人id
      money: that.data.orderInfo.total, //string	是	总金额
      mealBoxMoney: that.data.orderInfo.countBox, //string	是	餐盒费
      dispatchingMoney: that.data.orderInfo.dispatchingCost, //	string	是	配送费
      meetSubtract: that.data.orderInfo.meetMinus.minus, //string	是	满减减去金额
      goodsIds: ids,
      remark: that.data.remark //string	是	备注
    }, function(res) {
      console.log('---------生成订单中--------');
      if (res.data.code == 1) {
        let num = res.data.data.orderFormId;
        that.setData({
          orderId: num
        })
        that.wechatPay();
      }

    })
  },



  onPullDownRefresh: function() {

  },

  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  handleCancel1(){
    let that = this;
    that.setData({
      addrsShowStatus: false,
    })
    that.getAddrList();
  },
  changeAddress() {
    let that=this;
    that.setData({
      addrsShowStatus:true,
    })
    // wx.redirectTo({
    //   url: '../address/address',
    // });
  },
  //选择地址
  chooseAddr({detail}){
      let that=this;
      var idArr=that.data.idArr;
    var addrArr = that.data.AddrActions;
    if (idArr[detail.index]){
      for (let i in addrArr){
        if (addrArr[i].id == idArr[detail.index]){
           
          that.handleSuccess("设置成功");
          that.setData({
            addressId: idArr[detail.index],
            curReceivedInfo: addrArr[i].detail,
            addrsShowStatus:false,
          })
        }
      }
        
    }else{
      wx.navigateTo({
        url: '../address/address?orderData='+that.data.orderInfo,
      });
    }
    
  },
  getAddrList() {
    let that = this;
    let uid = wx.getStorageSync('uid');
    server.postReq("/mobile/PersonalCenter/lookReceiverAddress", {
      userId: uid
    }, function (res) {
      if (res.data.code == 1) {
        // that.setData({
        //   addrList: res.data.data
        // })
        let data=res.data.data;
        var AddrActions=new Array();
        var idArr=new Array();
        for(let j in data){
    
           var newobj=new Object();
          newobj.name = data[j].name+","+data[j].site;
          newobj.id = data[j].id;
          idArr.push(data[j].id);
          newobj.detail=data[j];
          AddrActions.push(newobj);
        };
        var last={
          name:"新增地址",
          icon:'add'

        }
        AddrActions.push(last);
        that.setData({
          AddrActions: AddrActions,
          idArr:idArr,
        })
      }
    })
  },
  pay(obj) {
 
    var that = this;
 
      wx.requestPayment({
 
        "timeStamp": obj.timeStamp+'',
        "nonceStr": obj.nonceStr + '',
        "package":obj.package,
        "signType":"MD5",
        "paySign": obj.sign+'',
        success: function(res){
          wx.switchTab({
            url: '../index/index',
          })
          },
        fail: function(err) {
          wx.switchTab({
            url: '../index/index',
           })
        },

      })


  },
  wechatPay() {
    var that = this;
    console.log("--------------付款中--------------")
    server.postReq('/model/wxPay/api/wxXCX/createOrder', {
      openid: that.data.openid,
      orderFormId: that.data.orderId,
      attach: 1
    }, function(res) {
 
      if (res.data.code == "100") {
        that.pay(res.data.msg);

      }
    })
  },
  getOpenId: function() {
    var that = this;
    
    that.setData({
      openid: wx.getStorageSync("openid")
    });

  },
  getOrderInfo(){

  },
  handleText(msg) {
    $Toast({
      content: msg
    });
  },
  handleSuccess(successMsg) {
    $Toast({
      content: successMsg,
      type: 'success'
    });
  },
  handleWarning() {
    $Toast({
      content: '警告的提示',
      type: 'warning'
    });
  },
  handleError() {
    $Toast({
      content: '错误的提示',
      type: 'error'
    });
  },
  handleLoading() {
    $Toast({
      content: '加载中',
      type: 'loading'
    });
  },
})